﻿#region Copyright (c) 2013-06, Olaf Kober <amarok.projects@gmail.com>
//================================================================================
//	Permission is hereby granted, free of charge, to any person obtaining a copy
//	of this software and associated documentation files (the "Software"), to deal
//	in the Software without restriction, including without limitation the rights
//	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//	copies of the Software, and to permit persons to whom the Software is
//	furnished to do so, subject to the following conditions:
//
//	The above copyright notice and this permission notice shall be included in
//	all copies or substantial portions of the Software.
//
//	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//	THE SOFTWARE.
//================================================================================
#endregion

using System;
using System.Reflection;
using Amarok.Agents;
using Amarok.Presentation.Resources;


namespace Amarok.Presentation
{
	/// <summary>
	/// This type implements the default factory that is capable to spawn new controller instances.
	/// </summary>
	public class DefaultControllerFactory :
		IControllerFactory
	{
		#region ++ IControllerFactory Interface ++

		/// <summary>
		/// Spawns a new instance of the given controller type.
		/// </summary>
		/// 
		/// <param name="controllerType">
		/// The type of controller to spawn. This must be a sub-class of <see cref="Controller"/>.</param>
		/// <param name="view">
		/// A reference to the view with which the controller should be associated.</param>
		/// <param name="viewModel">
		/// The view model that is used as intermediate between controller and view.</param>
		/// <param name="environment">
		/// The agent environment to be supplied to the new controller instance.</param>
		/// <param name="options">
		/// The agent options to be supplied to the new controller instance.</param>
		/// 
		/// <returns>
		/// A reference to the newly spawned controller instance.</returns>
		/// 
		/// <exception cref="ArgumentNullException">
		/// A null reference was passed to a method that did not accept it as a valid argument.</exception>
		/// <exception cref="ArgumentException">
		/// A value was passed to a method that did not accept it as a valid argument, because 
		/// the value representing a type must be a sub-class of <see cref="Controller"/>.</exception>
		/// <exception cref="ControllerSpawnException">
		/// An instance of the specified controller type cannot be instantiated, because the controller type does not 
		/// provide a controller-specific constructor that accepts agent environment, agent options, view and view model. 
		/// Provide a constructor with following signature: Controller(AgentEnvironment, AgentOptions, IView, Object).</exception>
		/// <exception cref="ControllerSpawnException">
		/// An instance of the specified controller type could not be spawned. Refer to the inner exception 
		/// for more information.</exception>
		public IController SpawnController(
			Type controllerType,
			IView view,
			Object viewModel,
			AgentEnvironment environment,
			AgentOptions options)
		{
			Verify.IsSubclassOf(controllerType, typeof(Controller), "controllerType");
			Verify.NotNull(view, "view");
			Verify.NotNull(viewModel, "viewModel");
			Verify.NotNull(environment, "environment");
			Verify.NotNull(options, "options");

			try
			{
				var controller = OnCreate(controllerType, view, viewModel, environment, options);

				OnConnect(controller, environment, options);

				return controller;
			}
			catch (MissingMethodException exception)
			{
				throw new ControllerSpawnException(
					ExceptionResources.ControllerTypeDoesNotProvideControllerConstructor,
					exception);
			}
			catch (Exception exception)
			{
				throw new ControllerSpawnException(
					ExceptionResources.ControllerSpawnFailure,
					exception);
			}
		}

		#endregion

		#region ## Overridable Methods ##

		/// <summary>
		/// This method is called to instantiate a new controller.
		/// </summary>
		/// 
		/// <param name="controllerType">
		/// The type of agent to spawn. This must be a sub-class of <see cref="Agent"/>.</param>
		/// <param name="view">
		/// A reference to the view with which the controller should be associated.</param>
		/// <param name="viewModel">
		/// The view model that is used as intermediate between controller and view.</param>
		/// <param name="environment">
		/// The agent environment to be supplied to the new agent instance.</param>
		/// <param name="options">
		/// The agent options to be supplied to the new agent instance.</param>
		/// 
		/// <returns>
		/// A reference to the newly spawned agent instance.</returns>
		protected virtual IController OnCreate(Type controllerType, IView view, Object viewModel,
			AgentEnvironment environment, AgentOptions options)
		{
			return (IController)Activator.CreateInstance(
				controllerType,
				BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance,
				null,
				new Object[] { environment, options, view, viewModel },
				null);
		}

		/// <summary>
		/// This method is called to connected the newly spawned controller to the message bus.
		/// </summary>
		/// 
		/// <param name="controller">
		/// The newly spawned controller instance.</param>
		/// <param name="environment">
		/// The agent environment to be supplied to the new agent instance.</param>
		/// <param name="options">
		/// The agent options to be supplied to the new agent instance.</param>
		protected virtual void OnConnect(IController controller, AgentEnvironment environment, AgentOptions options)
		{
			var runtimeEnvironment = environment as RuntimeEnvironment;

			if (runtimeEnvironment == null)
				return;

			if (MessageBusConnectedAttribute.IsDefined(controller.GetType()) == false)
				return;

			runtimeEnvironment.MessageBus.Connect(controller);
		}

		#endregion

	}
}
